<template>
  <div class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50">
    <div class="container mx-auto px-4 py-8">
      <!-- 页面标题 -->
      <div class="mb-8">
        <div class="flex justify-between items-center">
          <div class="text-center md:text-left">
            <div class="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-r from-blue-600 to-purple-600 rounded-2xl mb-4 shadow-lg">
              <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
              </svg>
            </div>
            <h1 class="text-4xl font-bold bg-gradient-to-r from-gray-900 to-gray-700 bg-clip-text text-transparent mb-2">题目管理</h1>
            <p class="text-gray-600 text-lg">管理系统题目和测试用例</p>
          </div>
          <button
            class="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-xl hover:from-blue-700 hover:to-purple-700 transition-all duration-200 transform hover:scale-105 shadow-lg hover:shadow-xl"
            @click="createQuestion"
          >
            <svg class="w-5 h-5 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
            </svg>
            添加题目
          </button>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg p-6 mb-6 border border-white/20">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
          <div class="md:col-span-2">
            <div class="relative">
              <input
                v-model="searchQuery"
                type="text"
                placeholder="搜索题目..."
                class="w-full pl-12 pr-4 py-3 border border-gray-200/50 rounded-xl bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-blue-500/30 focus:border-blue-500 transition-all duration-200 shadow-sm hover:shadow-md"
                @input="handleSearch"
              />
              <svg class="absolute left-4 top-3.5 h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
              </svg>
            </div>
          </div>

          <div>
            <select
              v-model="selectedDifficulty"
              class="w-full px-4 py-3 border border-gray-200/50 rounded-xl bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-blue-500/30 focus:border-blue-500 transition-all duration-200 shadow-sm hover:shadow-md"
              @change="handleFilter"
            >
              <option value="">所有难度</option>
              <option value="Easy">简单</option>
              <option value="Medium">中等</option>
              <option value="Hard">困难</option>
            </select>
          </div>

          <div>
            <select
              v-model="selectedStatus"
              class="w-full px-4 py-3 border border-gray-200/50 rounded-xl bg-white/80 backdrop-blur-sm focus:ring-2 focus:ring-blue-500/30 focus:border-blue-500 transition-all duration-200 shadow-sm hover:shadow-md"
              @change="handleFilter"
            >
              <option value="">所有状态</option>
              <option value="published">已发布</option>
              <option value="draft">草稿</option>
              <option value="archived">已归档</option>
            </select>
          </div>
        </div>
      </div>

      <!-- 题目列表 -->
      <div class="bg-white/80 backdrop-blur-sm rounded-2xl shadow-lg overflow-hidden border border-white/20">
        <!-- 列表头部 -->
        <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b border-gray-200/50">
          <div class="flex items-center justify-between">
            <h3 class="text-lg font-semibold text-gray-900">题目列表</h3>
            <span class="text-sm text-gray-600">共 {{ totalQuestions }} 道题目</span>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="flex justify-center items-center py-12">
          <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
          <span class="ml-3 text-gray-600">加载中...</span>
        </div>

        <!-- 错误状态 -->
        <div v-else-if="error" class="text-center py-12">
          <div class="text-red-500 mb-4">{{ error }}</div>
          <button @click="loadQuestions" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">
            重试
          </button>
        </div>

        <!-- 卡片列表 -->
        <div v-else class="p-6">
          <div class="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
            <div
              v-for="(question, index) in questions"
              :key="question.id"
              class="bg-white/80 backdrop-blur-sm rounded-xl shadow-md hover:shadow-lg transition-all duration-300 transform hover:scale-105 border border-gray-200/50 overflow-hidden"
            >
              <!-- 卡片头部 -->
              <div class="p-6 border-b border-gray-200/50">
                <div class="flex items-start justify-between mb-3">
                  <div class="flex-1">
                    <h4 class="text-lg font-semibold text-gray-900 mb-1">
                      {{ getQuestionNumber(index) }}. {{ question.title }}
                    </h4>
                    <p class="text-sm text-gray-600 line-clamp-2">
                      {{ question.content ? question.content.substring(0, 80) + '...' : '暂无描述' }}
                    </p>
                  </div>
                </div>
                
                <!-- 标签区域 -->
                <div class="flex flex-wrap gap-2">
                  <span
                    :class="[
                      'px-3 py-1 rounded-full text-xs font-semibold',
                      question.difficulty === 'Easy' ? 'bg-green-100 text-green-800' :
                      question.difficulty === 'Medium' ? 'bg-yellow-100 text-yellow-800' :
                      'bg-red-100 text-red-800'
                    ]"
                  >
                    {{ question.difficulty === 'Easy' ? '简单' : question.difficulty === 'Medium' ? '中等' : '困难' }}
                  </span>
                  <span
                    :class="[
                      'px-3 py-1 rounded-full text-xs font-semibold',
                      question.status === 'published' ? 'bg-green-100 text-green-800' :
                      question.status === 'draft' ? 'bg-yellow-100 text-yellow-800' :
                      'bg-gray-100 text-gray-800'
                    ]"
                  >
                    {{ question.status === 'published' ? '已发布' : question.status === 'draft' ? '草稿' : '已归档' }}
                  </span>
                </div>
              </div>

              <!-- 卡片内容 -->
              <div class="p-6">
                <div class="grid grid-cols-2 gap-4 mb-4">
                  <div class="text-center">
                      <div class="text-2xl font-bold text-blue-600">{{ (question.acceptance_rate * 100).toFixed(2) || 0 }}%</div>
                    <div class="text-xs text-gray-500">通过率</div>
                  </div>
                  <div class="text-center">
                    <div class="text-sm text-gray-600">{{ formatDate(question.created_at) }}</div>
                    <div class="text-xs text-gray-500">创建时间</div>
                  </div>
                </div>

                <!-- 操作按钮 -->
                <div class="flex flex-wrap gap-2">
                  <button
                    class="flex-1 px-3 py-2 bg-blue-100 text-blue-700 hover:bg-blue-200 rounded-lg text-sm font-medium transition-colors"
                    @click="editQuestion(question)"
                  >
                    编辑
                  </button>
                  <button
                    class="flex-1 px-3 py-2 bg-green-100 text-green-700 hover:bg-green-200 rounded-lg text-sm font-medium transition-colors"
                    @click="viewQuestion(question)"
                  >
                    查看
                  </button>
                  <button
                    v-if="question.status === 'published'"
                    class="flex-1 px-3 py-2 bg-yellow-100 text-yellow-700 hover:bg-yellow-200 rounded-lg text-sm font-medium transition-colors"
                    @click="unpublishQuestion(question)"
                  >
                    下架
                  </button>
                  <button
                    v-else
                    class="flex-1 px-3 py-2 bg-green-100 text-green-700 hover:bg-green-200 rounded-lg text-sm font-medium transition-colors"
                    @click="publishQuestion(question)"
                  >
                    发布
                  </button>
                  <button
                    class="flex-1 px-3 py-2 bg-red-100 text-red-700 hover:bg-red-200 rounded-lg text-sm font-medium transition-colors"
                    @click="deleteQuestion(question)"
                  >
                    删除
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-if="!loading && questions.length === 0" class="text-center py-12">
            <div class="inline-flex items-center justify-center w-24 h-24 bg-gradient-to-r from-gray-100 to-gray-200 rounded-full mb-6">
              <svg class="w-12 h-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
              </svg>
            </div>
            <h3 class="text-xl font-semibold text-gray-900 mb-2">暂无题目</h3>
            <p class="text-gray-500 mb-6">没有找到符合条件的题目</p>
            <button
              class="px-6 py-3 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-xl hover:from-blue-700 hover:to-purple-700 transition-all duration-200 transform hover:scale-105 shadow-lg"
              @click="createQuestion"
            >
              创建第一道题目
            </button>
          </div>
        </div>

        <!-- 分页 -->
        <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-t border-gray-200/50">
          <div class="flex items-center justify-between">
            <div class="text-sm text-gray-600">
              显示第
              <span class="font-semibold text-gray-900">{{ (currentPage - 1) * pageSize + 1 }}</span>
              到
              <span class="font-semibold text-gray-900">{{ Math.min(currentPage * pageSize, totalQuestions) }}</span>
              条，共
              <span class="font-semibold text-gray-900">{{ totalQuestions }}</span>
              条记录
            </div>
            <div class="flex items-center space-x-2">
              <button
                :disabled="currentPage === 1"
                class="px-4 py-2 rounded-xl text-sm font-medium transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed bg-white/80 backdrop-blur-sm border border-gray-200/50 text-gray-700 hover:bg-gray-50 hover:shadow-md"
                @click="goToPage(currentPage - 1)"
              >
                <svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                </svg>
                上一页
              </button>
              
              <div class="flex space-x-1">
                <button
                  v-for="page in visiblePages"
                  :key="page"
                  :class="[
                    'px-4 py-2 rounded-xl text-sm font-medium transition-all duration-200',
                    page === currentPage
                      ? 'bg-gradient-to-r from-blue-500 to-blue-600 text-white shadow-md'
                      : 'bg-white/80 backdrop-blur-sm border border-gray-200/50 text-gray-700 hover:bg-gray-50 hover:shadow-md'
                  ]"
                  @click="goToPage(page)"
                >
                  {{ page }}
                </button>
              </div>
              
              <button
                :disabled="currentPage === totalPages"
                class="px-4 py-2 rounded-xl text-sm font-medium transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed bg-white/80 backdrop-blur-sm border border-gray-200/50 text-gray-700 hover:bg-gray-50 hover:shadow-md"
                @click="goToPage(currentPage + 1)"
              >
                下一页
                <svg class="w-4 h-4 inline ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                </svg>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { adminApi } from '@/api/admin'

const router = useRouter()

// 响应式数据
const searchQuery = ref('')
const selectedDifficulty = ref('')
const selectedStatus = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const loading = ref(false)
const error = ref('')

// 题目数据
const questions = ref<any[]>([])
const totalQuestions = ref(0)

// 计算属性
const totalPages = computed(() => Math.ceil(totalQuestions.value / pageSize.value))

const visiblePages = computed(() => {
  const pages = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  
  return pages
})

// 方法
const loadQuestions = async () => {
  loading.value = true
  error.value = ''
  
  try {
    const params = {
      page: currentPage.value,
      page_size: pageSize.value,
      difficulty: selectedDifficulty.value || undefined,
      status: selectedStatus.value || undefined,
      search: searchQuery.value || undefined
    }
    
    const response = await adminApi.getQuestions(params)
    
    if (response.data) {
      questions.value = response.data.questions || []
      totalQuestions.value = response.data.total || 0
    }
  } catch (err: any) {
    error.value = err.message || '加载题目列表失败'
    console.error('加载题目列表失败:', err)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  loadQuestions()
}

const handleFilter = () => {
  currentPage.value = 1
  loadQuestions()
}

const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    loadQuestions()
  }
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 计算题目序号
const getQuestionNumber = (index: number) => {
  return (currentPage.value - 1) * pageSize.value + index + 1
}

const createQuestion = () => {
  router.push('/questions/create')
}

const editQuestion = (question: any) => {
  router.push(`/admin/questions/${question.id}/edit`)
}

const viewQuestion = (question: any) => {
  router.push(`/questions/${question.id}`)
}

const publishQuestion = async (question: any) => {
  if (confirm(`确定要发布题目 "${question.title}" 吗？`)) {
    try {
      const response = await adminApi.publishQuestion(question.id)
      if (response.data?.success) {
        question.status = 'published'
        // 显示成功消息
        console.log('题目发布成功')
        // 重新加载题目列表
        loadQuestions()
      }
    } catch (error: any) {
      console.error('发布题目失败:', error)
      alert('发布题目失败: ' + (error.message || '未知错误'))
    }
  }
}

const unpublishQuestion = async (question: any) => {
  if (confirm(`确定要下架题目 "${question.title}" 吗？`)) {
    try {
      const response = await adminApi.unpublishQuestion(question.id)
      if (response.data?.success) {
        question.status = 'draft'
        // 显示成功消息
        console.log('题目下架成功')
        // 重新加载题目列表
        loadQuestions()
      }
    } catch (error: any) {
      console.error('下架题目失败:', error)
      alert('下架题目失败: ' + (error.message || '未知错误'))
    }
  }
}

const deleteQuestion = async (question: any) => {
  if (confirm(`确定要删除题目 "${question.title}" 吗？此操作不可恢复！`)) {
    try {
      const response = await adminApi.deleteQuestion(question.id)
      if (response.data?.success) {
        console.log('题目删除成功')
        // 重新加载题目列表以确保序号正确
        await loadQuestions()
      }
    } catch (error: any) {
      console.error('删除题目失败:', error)
      alert('删除题目失败: ' + (error.message || '未知错误'))
    }
  }
}

onMounted(() => {
  loadQuestions()
})
</script>

